﻿using AutoMapper;
using FreeSql;
using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using MySqlX.XDevAPI.Common;
using NPOI.SS.Formula.Functions;

namespace Darius.API.Application.Commands
{
    public class RoleCreateHandler : IRequestHandler<RoleCreateCommand, IMES.Common.Dtos.Result>
    {

        private readonly IMapper mapper;
        private readonly IBaseRepositorys<Roles> roleRepository;
        private readonly ILogger<RoleCreateHandler> logger;

        public RoleCreateHandler(IBaseRepositorys<Roles> roleRepository, IMapper mapper, ILogger<RoleCreateHandler> logger)
        {
            this.roleRepository = roleRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IMES.Common.Dtos.Result> Handle(RoleCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new IMES.Common.Dtos.Result() { Code = (int)CodeEnum.add };
                Roles role = mapper.Map<Roles>(request);
                var list = roleRepository.Add(role);
                result.Messege = "角色添加成功";
                result.Code = list;
                logger.LogInformation("角色添加成功");
                return result;

            }
            catch (Exception ex)
            {
                logger.LogError(ex, "角色添加失败");
                return new IMES.Common.Dtos.Result() { Code = (int)CodeEnum.error, Messege = "角色添加失败" };
            }
        }

    }
}

